package com.ruoyi.deviceLog.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.device.domain.Device;
import com.ruoyi.device.mapper.DeviceMapper;
import com.ruoyi.deviceLog.domain.DeviceLog;
import com.ruoyi.deviceLog.mapper.DeviceLogMapper;
import com.ruoyi.deviceLog.service.DeviceLogService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 公司设备日常检查记录Service业务层处理
 *
 * @author zjh
 * @date 2022-05-10
 */
@Service
public class DeviceLogServiceImpl implements DeviceLogService {
    @Autowired
    private DeviceLogMapper deviceLogMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询公司设备日常检查记录
     *
     * @param logId 公司设备日常检查记录ID
     * @return 公司设备日常检查记录
     */
    @Override
    public DeviceLog selectDeviceLogById(Long logId) {
        return deviceLogMapper.selectDeviceLogById(logId);
    }

    /**
     * 查询公司设备日常检查记录列表
     *
     * @param deviceLog 公司设备日常检查记录
     * @return 公司设备日常检查记录
     */
    @Override
    public List<DeviceLog> selectDeviceLogByComId(DeviceLog deviceLog) {
        return deviceLogMapper.selectDeviceLogByComId(deviceLog);
    }

    /**
     * 查询公司设备日常检查记录列表
     *
     * @param deviceLog 公司设备日常检查记录
     * @return 公司设备日常检查记录集合
     */
    @Override
    public List<DeviceLog> selectDeviceLogByComIds(DeviceLog deviceLog) {
        return deviceLogMapper.selectDeviceLogByComIds(deviceLog);
    }

    /**
     * 新增公司设备日常检查记录
     *
     * @return 结果
     */
    @Override
    public int insertDeviceLog() {
        List<DeviceLog> deviceLogs = deviceLogMapper.selectForInsert();
        List<DeviceLog> deviceLogList = new ArrayList<>();
        Date time = DateUtils.getNowDate();
        if (deviceLogs != null) {
            for (DeviceLog deviceLog : deviceLogs) {
                deviceLog.setDeviceStatus("1");
                deviceLog.setCreateTime(time);
                deviceLog.setCreateBy("admin");
                deviceLogList.add(deviceLog);
            }
        }
        return deviceLogMapper.insertDeviceLogs(deviceLogList);
    }

    /**
     * 修改公司设备日常检查记录
     *
     * @return 结果
     */
    @Override
    public int updateDeviceLog(String dateTime, String key, String status) throws ParseException {
        DeviceLog deviceLog = new DeviceLog();
        if ("1".equals(status)) {
            deviceLog.setDeviceStatus("2");
        } else {
            deviceLog.setDeviceStatus("1");
        }
        deviceLog.setCompanyId(SecurityUtils.getLoginUser().getCompanyId());
        deviceLog.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateTime));
        deviceLog.setDeviceId(Long.parseLong(key));
        deviceLog.setUpdateTime(DateUtils.getNowDate());
        deviceLog.setUpdateBy(SecurityUtils.getLoginUser().getNickName());
        return deviceLogMapper.updateDeviceLog(deviceLog);
    }

    /**
     * 删除公司设备日常检查记录对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteDeviceLogByIds(String ids) {
        return deviceLogMapper.deleteDeviceLogByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除公司设备日常检查记录信息
     *
     * @param logId 公司设备日常检查记录ID
     * @return 结果
     */
    @Override
    public int deleteDeviceLogById(Long logId) {
        return deviceLogMapper.deleteDeviceLogById(logId);
    }

    /**
     * 下载模板
     */
    public String exportTemp() {
        HSSFWorkbook workbook = new HSSFWorkbook();// 创建Excel文件(Workbook)

        HSSFSheet sheet = null;// 创建工作表(Sheet)

        sheet = workbook.createSheet("sheet1");// 创建工作表(Sheet)

        HSSFRow row0 = sheet.createRow(0);
        DeviceLog deviceLog1 = new DeviceLog();

        Long companyId = SecurityUtils.getLoginUser().getCompanyId();
        deviceLog1.setCompanyId(companyId);

        List<Device> devices = deviceMapper.selectDeviceForLog(companyId);
        List<DeviceLog> deviceLogs = deviceLogMapper.selectDeviceLogByComId(deviceLog1);
        List<String> dataList = new ArrayList<>();
//        Map<Integer, List<String>> map = new HashMap<>();
        for (DeviceLog deviceLog : deviceLogs) {
            SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
            sdf.applyPattern("yyyy-MM-dd HH:mm");// a为am/pm的标记
            Date nowTime = deviceLog.getCreateTime();
            String data = sdf.format(nowTime);
            if (dataList.contains(data)) {
                continue;
            } else {
                dataList.add(data);
            }
        }
        int rowSize = devices.size() + 1;
        int dataSize = dataList.size();
        String[] dateOfIndex = new String[dataSize];
        String[] valueOfIndex = new String[rowSize];
        int s = 0;
        for (String list : dataList) {
            dateOfIndex[s] = list;
            s++;
        }
        // 表格的头
        List<String> haed1 = new LinkedList<>();
        Map<String, Object> titleMap = new LinkedHashMap<>();
        for (int i = 0; i < dataList.size(); i++) {
            int myParameter = 0;
            if (i == 0) {
                haed1.add("日期");
                valueOfIndex[myParameter] = "dateTime";
                myParameter++;
            }
            for (Device device : devices) {
                Long deviceId = device.getDeviceId();
                String deviceName = device.getDeviceItem();
                if (i == 0) {
                    titleMap.put(deviceId.toString(), deviceName);
                    valueOfIndex[myParameter] = device.getDeviceId().toString();
                    myParameter++;
                    haed1.add(deviceName);
                }
            }
        }
        for (int u = 0; u < dataSize; u++) {
            HSSFRow thisRow = sheet.createRow(u + 1);
            List<String> row = new LinkedList<>();
            row.add(dateOfIndex[u]);
            for (int r = 1; r < rowSize; r++) {
                row.add("-");
                for (DeviceLog deviceLog : deviceLogs) {
                    SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
                    sdf.applyPattern("yyyy-MM-dd HH:mm");// a为am/pm的标记
                    Date nowTime = deviceLog.getCreateTime();
                    String data = sdf.format(nowTime);
                    if (valueOfIndex[r].equals(deviceLog.getDeviceId().toString()) && dateOfIndex[u].equals(data)) {
                        if (deviceLog.getDeviceStatus().equals("1")) {
                            row.set(r, "正常");
                        } else {
                            row.set(r, "更换");
                        }
                    }
                }
            }
            Map<String, List> thisHead = new HashMap<>();
            thisHead.put("公司设备日常检查记录", row);
            for (Map.Entry<String, List> entry : thisHead.entrySet()) {
                HSSFCellStyle style = workbook.createCellStyle();
                style.setAlignment(HorizontalAlignment.CENTER);//水平居中
                style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
                style.setBorderBottom(BorderStyle.THIN);
                style.setBottomBorderColor(IndexedColors.AUTOMATIC.getIndex());
                style.setBorderRight(BorderStyle.THIN);
                style.setRightBorderColor(IndexedColors.AUTOMATIC.getIndex());

                style.setBorderTop(BorderStyle.THIN);
                style.setTopBorderColor(IndexedColors.AUTOMATIC.getIndex());
//            sheet.setColumnWidth(i, 25 * 256);
                int i = 0;
                for (int j = 0; j < entry.getValue().size(); j++) {
                    HSSFCell cell1 = thisRow.createCell(i);
                    cell1.setCellStyle(style);
                    cell1.setCellValue(entry.getValue().get(j).toString());
                    sheet.setColumnWidth(i, 25 * 256);
                    i++;
                }
            }
        }

        Map<String, List> haed = new HashMap<>();
        haed.put("公司设备日常检查记录", haed1);

        int i = 0;
        for (Map.Entry<String, List> entry : haed.entrySet()) {

            HSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);//水平居中
            style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
            style.setBorderBottom(BorderStyle.THIN);
            style.setBottomBorderColor(IndexedColors.AUTOMATIC.getIndex());
            style.setBorderRight(BorderStyle.THIN);
            style.setRightBorderColor(IndexedColors.AUTOMATIC.getIndex());

            style.setBorderTop(BorderStyle.THIN);
            style.setTopBorderColor(IndexedColors.AUTOMATIC.getIndex());
//            sheet.setColumnWidth(i, 25 * 256);
            for (int j = 0; j < entry.getValue().size(); j++) {
                HSSFCell cell1 = row0.createCell(i);
                cell1.setCellStyle(style);
                cell1.setCellValue(entry.getValue().get(j).toString());
                sheet.setColumnWidth(i, 25 * 256);
                i++;
            }
        }

        String localPath = RuoYiConfig.getProfile() + "/download/" + UUID.randomUUID().toString();

        // 生成文件夹
        File file = new File(localPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        // 填充数据
        try {
            FileOutputStream out = new FileOutputStream(localPath + "/" + "仓储设备设施查验.xls");
            workbook.write(out); // 保存Excel文件
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return localPath + "/" + "仓储设备设施查验.xls";

    }
}